package com.example.config;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.api.PropertyKeyConst;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
import java.util.Properties;

@Configuration
public class SentinelRuleConfig {

    @Value("${spring.cloud.nacos.discovery.server-addr}")
    private String nacosServerAddr;

    @Value("${spring.cloud.nacos.discovery.username}")
    private String nacosUsername;

    @Value("${spring.cloud.nacos.discovery.password}")
    private String nacosPassword;

    // 限流规则数据源（从Nacos加载，带认证信息）
    @Bean
    public ReadableDataSource<String, List<FlowRule>> flowRuleDataSource() {
        String dataId = "sky-sentinel-flow-rules";
        String groupId = "SENTINEL_GROUP";

        // 1. 构建Nacos配置属性（包含认证信息）
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, nacosServerAddr);
        properties.setProperty(PropertyKeyConst.USERNAME, nacosUsername);
        properties.setProperty(PropertyKeyConst.PASSWORD, nacosPassword);

        // 2. 使用带Properties参数的构造函数创建NacosDataSource
        ReadableDataSource<String, List<FlowRule>> dataSource = new NacosDataSource<>(
                properties,  // 传入包含认证信息的配置
                groupId,
                dataId,
                source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {})  // 解析规则
        );

        FlowRuleManager.register2Property(dataSource.getProperty());
        return dataSource;
    }

    // 熔断规则数据源（同理修改）
    @Bean
    public ReadableDataSource<String, List<DegradeRule>> degradeRuleDataSource() {
        String dataId = "sky-sentinel-degrade-rules";
        String groupId = "SENTINEL_GROUP";

        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, nacosServerAddr);
        properties.setProperty(PropertyKeyConst.USERNAME, nacosUsername);
        properties.setProperty(PropertyKeyConst.PASSWORD, nacosPassword);

        ReadableDataSource<String, List<DegradeRule>> dataSource = new NacosDataSource<>(
                properties,
                groupId,
                dataId,
                source -> JSON.parseObject(source, new TypeReference<List<DegradeRule>>() {})
        );

        DegradeRuleManager.register2Property(dataSource.getProperty());
        return dataSource;
    }
}